import com.alibaba.fastjson.JSON;
import httpclient.QuickStart;
import json.user;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import json.person;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet(urlPatterns = {"/login/dgut"})
public class HelloServlet extends HttpServlet {

   protected void doGet(HttpServletRequest req,
                         HttpServletResponse res) throws IOException, ServletException {
        doPost(req,res);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String token=req.getParameter("token");
        HttpSession session=req.getSession(true);
        List<NameValuePair> data=new ArrayList<>();
        data.add(new BasicNameValuePair("token",token));
        data.add(new BasicNameValuePair("appsecret","b3b52e43ccfd"));
        data.add(new BasicNameValuePair("appid","javaee"));
        data.add(new BasicNameValuePair("userip","localhost"));
        String po=QuickStart.post("https://cas.dgut.edu.cn/ssoapi/v2/checkToken",data);
        Jsonb jsonb = JsonbBuilder.create();
        user us=jsonb.fromJson(po,user.class);
        String access_token=us.getAccess_token();
        String openid=us.getOpenid();
        String js="{\n"+"error:1\n"+"message:access-token已过期或不存在\n}"+"\n";
        if(openid==null||access_token==null)
        {
            resp.getWriter().write(js);
        }
        else {
            List<NameValuePair> another=new ArrayList<>();
            another.add(new BasicNameValuePair("access_token",access_token));
            another.add(new BasicNameValuePair("openid",openid));
            js=QuickStart.post("https://cas.dgut.edu.cn/oauth/getUserInfo",another);
            person Person= JSON.parseObject(js,person.class);
            session.setAttribute("json",js);
            req.getSession().setAttribute("USER",Person);
            resp.sendRedirect("/login_dgut");
        }
    }
}